/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.ExecutedRules;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Predicate;
import it.polimi.games.epkb.entityClasses.GpiKpi;
import it.polimi.games.epkb.entityClasses.Rule;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class ExecutedRulesJpaController implements Serializable {

    public ExecutedRulesJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public ExecutedRulesJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(ExecutedRules executedRules) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Predicate idPredicateViolated = executedRules.getIdPredicateViolated();
            if (idPredicateViolated != null) {
                idPredicateViolated = em.getReference(idPredicateViolated.getClass(), idPredicateViolated.getId());
                executedRules.setIdPredicateViolated(idPredicateViolated);
            }
            GpiKpi idGPIKPIViolated = executedRules.getIdGPIKPIViolated();
            if (idGPIKPIViolated != null) {
                idGPIKPIViolated = em.getReference(idGPIKPIViolated.getClass(), idGPIKPIViolated.getId());
                executedRules.setIdGPIKPIViolated(idGPIKPIViolated);
            }
            Rule idRule = executedRules.getIdRule();
            if (idRule != null) {
                idRule = em.getReference(idRule.getClass(), idRule.getId());
                executedRules.setIdRule(idRule);
            }
            em.persist(executedRules);
            if (idPredicateViolated != null) {
                idPredicateViolated.getExecutedRulesCollection().add(executedRules);
                idPredicateViolated = em.merge(idPredicateViolated);
            }
            if (idGPIKPIViolated != null) {
                idGPIKPIViolated.getExecutedRulesCollection().add(executedRules);
                idGPIKPIViolated = em.merge(idGPIKPIViolated);
            }
            if (idRule != null) {
                idRule.getExecutedRulesCollection().add(executedRules);
                idRule = em.merge(idRule);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findExecutedRules(executedRules.getId()) != null) {
                throw new PreexistingEntityException("ExecutedRules " + executedRules + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(ExecutedRules executedRules) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ExecutedRules persistentExecutedRules = em.find(ExecutedRules.class, executedRules.getId());
            Predicate idPredicateViolatedOld = persistentExecutedRules.getIdPredicateViolated();
            Predicate idPredicateViolatedNew = executedRules.getIdPredicateViolated();
            GpiKpi idGPIKPIViolatedOld = persistentExecutedRules.getIdGPIKPIViolated();
            GpiKpi idGPIKPIViolatedNew = executedRules.getIdGPIKPIViolated();
            Rule idRuleOld = persistentExecutedRules.getIdRule();
            Rule idRuleNew = executedRules.getIdRule();
            if (idPredicateViolatedNew != null) {
                idPredicateViolatedNew = em.getReference(idPredicateViolatedNew.getClass(), idPredicateViolatedNew.getId());
                executedRules.setIdPredicateViolated(idPredicateViolatedNew);
            }
            if (idGPIKPIViolatedNew != null) {
                idGPIKPIViolatedNew = em.getReference(idGPIKPIViolatedNew.getClass(), idGPIKPIViolatedNew.getId());
                executedRules.setIdGPIKPIViolated(idGPIKPIViolatedNew);
            }
            if (idRuleNew != null) {
                idRuleNew = em.getReference(idRuleNew.getClass(), idRuleNew.getId());
                executedRules.setIdRule(idRuleNew);
            }
            executedRules = em.merge(executedRules);
            if (idPredicateViolatedOld != null && !idPredicateViolatedOld.equals(idPredicateViolatedNew)) {
                idPredicateViolatedOld.getExecutedRulesCollection().remove(executedRules);
                idPredicateViolatedOld = em.merge(idPredicateViolatedOld);
            }
            if (idPredicateViolatedNew != null && !idPredicateViolatedNew.equals(idPredicateViolatedOld)) {
                idPredicateViolatedNew.getExecutedRulesCollection().add(executedRules);
                idPredicateViolatedNew = em.merge(idPredicateViolatedNew);
            }
            if (idGPIKPIViolatedOld != null && !idGPIKPIViolatedOld.equals(idGPIKPIViolatedNew)) {
                idGPIKPIViolatedOld.getExecutedRulesCollection().remove(executedRules);
                idGPIKPIViolatedOld = em.merge(idGPIKPIViolatedOld);
            }
            if (idGPIKPIViolatedNew != null && !idGPIKPIViolatedNew.equals(idGPIKPIViolatedOld)) {
                idGPIKPIViolatedNew.getExecutedRulesCollection().add(executedRules);
                idGPIKPIViolatedNew = em.merge(idGPIKPIViolatedNew);
            }
            if (idRuleOld != null && !idRuleOld.equals(idRuleNew)) {
                idRuleOld.getExecutedRulesCollection().remove(executedRules);
                idRuleOld = em.merge(idRuleOld);
            }
            if (idRuleNew != null && !idRuleNew.equals(idRuleOld)) {
                idRuleNew.getExecutedRulesCollection().add(executedRules);
                idRuleNew = em.merge(idRuleNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = executedRules.getId();
                if (findExecutedRules(id) == null) {
                    throw new NonexistentEntityException("The executedRules with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ExecutedRules executedRules;
            try {
                executedRules = em.getReference(ExecutedRules.class, id);
                executedRules.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The executedRules with id " + id + " no longer exists.", enfe);
            }
            Predicate idPredicateViolated = executedRules.getIdPredicateViolated();
            if (idPredicateViolated != null) {
                idPredicateViolated.getExecutedRulesCollection().remove(executedRules);
                idPredicateViolated = em.merge(idPredicateViolated);
            }
            GpiKpi idGPIKPIViolated = executedRules.getIdGPIKPIViolated();
            if (idGPIKPIViolated != null) {
                idGPIKPIViolated.getExecutedRulesCollection().remove(executedRules);
                idGPIKPIViolated = em.merge(idGPIKPIViolated);
            }
            Rule idRule = executedRules.getIdRule();
            if (idRule != null) {
                idRule.getExecutedRulesCollection().remove(executedRules);
                idRule = em.merge(idRule);
            }
            em.remove(executedRules);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<ExecutedRules> findExecutedRulesEntities() {
        return findExecutedRulesEntities(true, -1, -1);
    }

    public List<ExecutedRules> findExecutedRulesEntities(int maxResults, int firstResult) {
        return findExecutedRulesEntities(false, maxResults, firstResult);
    }

    private List<ExecutedRules> findExecutedRulesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(ExecutedRules.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public ExecutedRules findExecutedRules(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(ExecutedRules.class, id);
        } finally {
            em.close();
        }
    }

    public int getExecutedRulesCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<ExecutedRules> rt = cq.from(ExecutedRules.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
